﻿using DotNetty.Common.Utilities;
using DotNetty.Transport.Channels;
using PSAMMatrixCloud.Common;
using System;

namespace PSAMMatrixCloud.TransferSecret.LaneMutual
{
    public class LaneServerHandler : SimpleChannelInboundHandler<Message> 
    {
        public override void ChannelActive(IChannelHandlerContext context)
        {
            //设置Channel会话信息
            IAttribute<SessionInfo> attribute = context.Channel.GetAttribute<SessionInfo>(LaneChannelManager.SESSION_KEY);

            SessionInfo sessionInfo = new SessionInfo
            {
                ChannelRemoteAddress = context.Channel.RemoteAddress,
                SessionID = Guid.NewGuid().ToString(),
                CreateTime = DateTime.Now,
                LastAccessTime = DateTime.Now,
            };
            attribute.SetIfAbsent(sessionInfo);
            LaneChannelManager.ChannelActive(context);
            //日志
             LogHelper.Info($"{context.Channel.RemoteAddress} 连接");
        }

        public override void ChannelInactive(IChannelHandlerContext context)
        {
            //删除会话
            string deviceID = LaneChannelManager.GetDeviceID(context.Channel);

            LaneChannelManager.Remove(context.Channel);

            //日志可禁用
            LogHelper.Info($"设备:{deviceID} 断开");
        }

        public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
        {
            context.CloseAsync();//关闭连接

            LogHelper.Error("会话出现异常", exception);
        }

        protected override void ChannelRead0(IChannelHandlerContext ctx, Message msg)
        {
            Message msgResult = new LaneControler().AnalyseControlerData(ctx.Channel, msg);//解析数据

            if (msgResult != null)
            {
                if (ctx.Channel.IsWritable)
                {
                    ctx.Channel.WriteAndFlushAsync(msgResult);//响应数据
                }
                else
                {
                    ctx.Channel.CloseAsync();
                    LaneChannelManager.Remove(ctx.Channel);
                }
            }
        }

        public override void ChannelRead(IChannelHandlerContext ctx, object msg)
        {
            //this.ChannelRead0(ctx, (Message)msg);
            base.ChannelRead(ctx, msg);
        }


        public override void ChannelReadComplete(IChannelHandlerContext context)
        {
            context.Flush();
        }
    }
}